package com.epro.dx.activity.order;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.epro.dx.R;
import com.epro.dx.activity.BaseFragmentActivity;
import com.epro.dx.activity.ChangeCountryActivity;
import com.epro.dx.util.MapUtil;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.OrderServiceProvider;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.CountryModel;
import com.weipu.common.facade.model.OrderModel;
import com.weipu.common.facade.support.service.TaskExecutor;
import com.weipu.common.facade.support.service.task.UnlockOrderTask;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.Logger;

import java.util.ArrayList;

/**
 * 修改订单
 * @author  qsc255
 * @version  [版本号, 2015-2-2]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class EditOrderActivity extends BaseFragmentActivity implements OnClickListener
{
    /**
     * 订单对象
     */
    private OrderModel orderModel;
    
    /**
     * 国家列表
     */
    private ArrayList<String> listCountry;
    
    /**
     * 国家码
     */
    private CountryModel countryModel;
    
    /**
     * 运送方式
     */
    private String shippingMethod;
    
    private Button btnconfirm;
    
    private EditText eFirstName;
    
    private EditText eLastName;
    
    private EditText eStreet1;
    
    private EditText eStreet2;
    
    private EditText eCity;
    
    private EditText eState;
    
    private TextView eCountry;
    
    private EditText ePostalCode;
    
    private EditText ePhoneNumber;
    
    private TextView eShippingMethod;
    
    private OrderModel.ShipAddress shipAddress;
    
    private String shippingMethodStr;
    
    private String clientIP;
    
    private BeginEditOrderAsyncTask beginEditOrderAsyncTask;
    
    /**
     * 获取订单详情接口
     */
    private OrderServiceProvider orderServiceProvider = ProviderFactory.createOrderServiceProvider();
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Tracker tracker = DXApplication.getContext().getTracker(TrackerName.APP_TRACKER);
		tracker.setScreenName(EditOrderActivity.class.getSimpleName());
		tracker.send(new HitBuilders.ScreenViewBuilder().build());
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_editorder);
        setTitleContent(getString(R.string.title_editorder));
        setLeftBtnContent(true, -1);
        Bundle bundle = getIntent().getExtras();
        orderModel = (OrderModel)bundle.getSerializable("orderModel");
        countryModel = (CountryModel)bundle.getSerializable("countryModel");
        shippingMethod = bundle.getString("shippingMethod");
        listCountry = (ArrayList<String>)MapUtil.getValues(countryModel.getAllCountry());
        getLocalWifiIp();
        initView();
        setData();
    }
    
    /** 初始化控件
     * @see [类、类#方法、类#成员]
     */
    private void initView()
    {
        eFirstName = (EditText)findViewById(R.id.first_name);
        eLastName = (EditText)findViewById(R.id.last_name);
        eStreet1 = (EditText)findViewById(R.id.street01);
        eStreet2 = (EditText)findViewById(R.id.street02);
        eCity = (EditText)findViewById(R.id.selector_city);
        eState = (EditText)findViewById(R.id.state_name);
        eCountry = (TextView)findViewById(R.id.country_name);
        ePostalCode = (EditText)findViewById(R.id.postal_code);
        ePhoneNumber = (EditText)findViewById(R.id.phonenumber);
        eShippingMethod = (TextView)findViewById(R.id.shipping_method);
        btnconfirm = (Button)findViewById(R.id.editor_confirm_btn);
        setEditTextIsAnable(true);
        eCountry.setOnClickListener(this);
        btnconfirm.setOnClickListener(this);
    }
    
    /**
     * 设置编辑框是否可用
     * @param enabled
     */
	private void setEditTextIsAnable(boolean enabled) {
		eFirstName.setEnabled(enabled);
		eLastName.setEnabled(enabled);
		eStreet1.setEnabled(enabled);
		eStreet2.setEnabled(enabled);
		eCity.setEnabled(enabled);
		eState.setEnabled(enabled);
		eCountry.setEnabled(enabled);
		ePostalCode.setEnabled(enabled);
		ePhoneNumber.setEnabled(enabled);
		btnconfirm.setEnabled(enabled);
	}
    
    /**
     * wifi已可以获取ip
     * 
     * @return [参数说明]
     * @return String [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public String getLocalWifiIp()
    {
        WifiManager wifi = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        if (null != info)
        {
            clientIP = intToIp(info.getIpAddress());
        }
        else
        {
            clientIP = "192.168.0.1";
        }
        return clientIP;
    }
    
    private String intToIp(int i)
    {
        
        return (i & 0xFF) + "." +
        
        ((i >> 8) & 0xFF) + "." +
        
        ((i >> 16) & 0xFF) + "." +
        
        (i >> 24 & 0xFF);
        
    }
    
    /**
     * 向页面添加数据
     * @see [类、类#方法、类#成员]
     */
    private void setData()
    {
        eFirstName.setText(orderModel.getShippingAddress().getFirstName());
        eLastName.setText(orderModel.getShippingAddress().getLastName());
        eStreet1.setText(orderModel.getShippingAddress().getStreet1());
        eStreet2.setText(orderModel.getShippingAddress().getStreet2());
        eCity.setText(orderModel.getShippingAddress().getCity());
        eState.setText(orderModel.getShippingAddress().getState());
        eCountry.setText((CharSequence)countryModel.getAllCountry().get(orderModel.getShippingAddress().getCountry()));
        ePostalCode.setText(orderModel.getShippingAddress().getPostalCode());
        ePhoneNumber.setText(orderModel.getShippingAddress().getPhoneNumber());
        eShippingMethod.setText(shippingMethod);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        //        if (resultCode == ServerConstant.Parameter.CHANGE_COUNTRY_RESULTCODE)
        //        {
        //            eCountry.setText(data.getStringExtra("countryName"));
        //        }
        switch (resultCode)
        {
            case ServerConstant.Parameter.CHANGE_COUNTRY_RESULTCODE:
                eCountry.setText(data.getStringExtra("countryName"));
                break;
            //            case ServerConstant.Parameter.CHANGE_SHIPPING_RESULTCODE:
            //                eShippingMethod.setText(data.getStringExtra("shippingName"));
            //                break;
            default:
                break;
        }
        
        super.onActivityResult(requestCode, resultCode, data);
    }
    
    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.editor_confirm_btn:
                check();
                break;
            case R.id.country_name:
                Bundle bundle = new Bundle();
                bundle.putStringArrayList("listCountry", listCountry);
                bundle.putString("countryName", eCountry.getText().toString());
                Intent intent = new Intent(this, ChangeCountryActivity.class);
                intent.putExtras(bundle);
                startActivityForResult(intent, ServerConstant.Parameter.CHANGE_COUNTRY_REQUESTCODE);
                break;
            default:
                break;
        }
    }
    
    /**
     * 保存编辑后的订单
     * 
     * @return void [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public void saveEditOrder()
    {
        shipAddress = new OrderModel.ShipAddress();
        shipAddress.setFirstName(eFirstName.getText().toString().trim());
        shipAddress.setLastName(eLastName.getText().toString().trim());
        shipAddress.setPhoneNumber(ePhoneNumber.getText().toString().trim());
        shipAddress.setPostalCode(ePostalCode.getText().toString().trim());
        shipAddress.setStreet1(eStreet1.getText().toString().trim());
        shipAddress.setStreet2(eStreet2.getText().toString().trim());
        shipAddress.setCity(eCity.getText().toString().trim());
        shipAddress.setState(eState.getText().toString().trim());
        String country = eCountry.getText().toString().trim();
        String countryCode = "";
        
        if (!"".equals(country) && null != country)
        {
            countryCode = (String)MapUtil.getKeyByValue(countryModel.getAllCountry(), country).get(0);
        }
        shipAddress.setCountry(countryCode);
        shippingMethodStr = shippingMethod;
        
        orderModel.setShippingAddress(shipAddress);
        orderModel.setShippingMethod(shippingMethodStr);
        beginEditOrderAsyncTask = new BeginEditOrderAsyncTask();
        beginEditOrderAsyncTask.execute();
    }
    
    /**
     * 
     * 校验修改订单输入参数
     * 
     * @return void [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public void check()
    {
        if (TextUtils.isEmpty(eFirstName.getText().toString().trim()))
        {
            eFirstName.setText("");
            AlertToast.alert(EditOrderActivity.this, R.string.editorder_firstname_null, 1000);
            return;
        }
        else if (TextUtils.isEmpty(eLastName.getText().toString().trim()))
        {
            eLastName.setText("");
            AlertToast.alert(EditOrderActivity.this, R.string.editorder_lastname_null, 1000);
            return;
        }
        else if (TextUtils.isEmpty(eStreet1.getText().toString().trim()))
        {
            eStreet1.setText("");
            AlertToast.alert(EditOrderActivity.this, R.string.editorder_street1_null, 1000);
            return;
        }
        else if (TextUtils.isEmpty(eCity.getText().toString().trim()))
        {
            eCity.setText("");
            AlertToast.alert(EditOrderActivity.this, R.string.editorder_city_null, 1000);
            return;
        }
        else if (TextUtils.isEmpty(eState.getText().toString().trim()))
        {
            eState.setText("");
            AlertToast.alert(EditOrderActivity.this, R.string.editorder_state_null, 1000);
            return;
        }
        // 暂时不能确定是否需要此处提示
        else if (TextUtils.isEmpty(eCountry.getText().toString().trim()))
        {
            
            AlertToast.alert(EditOrderActivity.this, R.string.editorder_country_null, 1000);
            return;
        }
        else if (TextUtils.isEmpty(ePostalCode.getText().toString().trim()))
        {
            ePostalCode.setText("");
            AlertToast.alert(EditOrderActivity.this, R.string.editorder_postalcode_null, 1000);
            return;
        }
        else if (TextUtils.isEmpty(ePhoneNumber.getText().toString().trim()))
        {
            ePhoneNumber.setText("");
            AlertToast.alert(EditOrderActivity.this, R.string.editorder_phonenumber_null, 1000);
            return;
        }
        // 暂时不能确定是否需要此处提示
        else if (TextUtils.isEmpty(eShippingMethod.getText()))
        {
            AlertToast.alert(EditOrderActivity.this, R.string.editorder_shippingmethod_null, 1000);
            return;
        }
        else
        {
            new AlertDialog.Builder(EditOrderActivity.this).setTitle(R.string.confirmation)
                .setCancelable(true)
                .setMessage(R.string.confirm_edit_order)
                .setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener()
                {
                    
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        saveEditOrder();
                    }
                    
                })
                .setNegativeButton(R.string.btn_no, new DialogInterface.OnClickListener()
                {
                    
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.dismiss();
                    }
                })
                .create()
                .show();
        }
    }
    
    /**
     * 修改收货地址
     * @author  qsc255
     * @version  [版本号, 2015-3-10]
     * @see  [相关类/方法]
     * @since  [产品/模块版本]
     */
    protected class BeginEditOrderAsyncTask extends AsyncTask<Void, Void, String>
    {
        @Override
        protected void onPreExecute()
        {
            //dialog.cancel();
        	showWaitingDialog();
            
        }
        
        @Override
        protected String doInBackground(Void... params)
        {
            try
            {
                orderServiceProvider.ChangeShippingOptions(clientIP,
                    orderModel.getOrderNumber(),
                    shipAddress,
                    shippingMethodStr);
            }
            catch (DxException e)
            {
                return e.getErrCode();
            }
            catch (Exception e)
            {
                Logger.e("EditOrderActivity", "BeginEditOrderAsyncTask", e);
            }
            //接口返回的状态码已经在数据解析时用DXException 的ErrorCode处理 若无异常返回就是0
            return "0";
        }
        
        @Override
        protected void onPostExecute(String result)
        {
           hideWaitingDialog();
            if ("0".equals(result))
            {
            	EditOrderActivity.this.finish();
                AlertToast.alert(EditOrderActivity.this, R.string.editorder_success, 1000);
                
                Intent intent = new Intent();
                
                intent.putExtra("orderModel", orderModel);
                
                EditOrderActivity.this.setResult(ServerConstant.Parameter.EDIT_RESULTCODE, intent);
                
                
            }
            else
            {
                // 编辑订单中有AU/EU/US商品的订单的地址
                if (result.equals(ServerConstant.ReturnCode.Payment.PAYMENT_ERROR_006002)
                    || result.equals(ServerConstant.ReturnCode.Payment.PAYMENT_ERROR_006003)
                    || result.equals(ServerConstant.ReturnCode.Payment.PAYMENT_ERROR_006004))
                {
                    new AlertDialog.Builder(EditOrderActivity.this).setTitle(getText(R.string.warning))
                        .setMessage(getText(ServerConstant.ReturnCode.MESSAGEMAP.get(result)))
                        .setPositiveButton(R.string.btn_yes, null)
                        .create()
                        .show();
                }
                else
                {
                    if (null == ServerConstant.ReturnCode.MESSAGEMAP.get(result))
                    {
                    	setEditTextIsAnable(false);
                        AlertToast.alert(EditOrderActivity.this, "Order could not be edited.");
                    }else{
                        AlertToast.alert(EditOrderActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                    }
                }
                
            }
            
        }
        
    }
    
    public void finish()
    {
        // 订单编辑结束后无论成功或失败都需要解锁订单
        TaskExecutor.doTaskInBackground(new UnlockOrderTask(orderModel.getOrderNumber(), "", ""));
        
        super.finish();
    }
    
}
